package com.biz.log;

import com.google.gson.*;
import lombok.extern.slf4j.*;
import org.aspectj.lang.*;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.*;
import org.springframework.boot.autoconfigure.condition.*;
import org.springframework.stereotype.*;

/**
 * @Description
 *    日志切面
 * @Author liuxi
 * @Date 2024/4/21
 **/
@Aspect
@Slf4j
@Component
@ConditionalOnProperty(name = {"log.aspect.enable"}, havingValue = "true", matchIfMissing = true)
public class LogAspect {

    /**
     * 切点
     */
    @Pointcut(
            "execution(* com.biz.*.controller.*Controller.*(..)) || " +
            "execution(* com.biz.*.service.*Service.*(..))")
    private void pointCut(){}

    /**
     * 切面
     */
    @Around("pointCut()")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        // 获取参数转为json
        Object[] reqArgs = pjp.getArgs();
        String req = new Gson().toJson(reqArgs);
        // 获取切点
        MethodSignature methodSignature = (MethodSignature) pjp.getSignature();
        String methodName = methodSignature.getDeclaringType().getName() + "." + methodSignature.getName();
        log.info("{}, req:{}", methodName, req);
        long startTime = System.currentTimeMillis();
        // 开始执行
        Object responseObj = pjp.proceed();
        String resp = new Gson().toJson(responseObj);
        long endTime = System.currentTimeMillis();
        log.info("{}, response: {}, costTime: {}", methodName, resp, endTime - startTime);
        return responseObj;
    }

}
